package org.teamswift.crow.rbac.security;

import com.google.common.base.Strings;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.teamswift.crow.rbac.entity.CrowUser;

public class PasswordHelper {

    public static final RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

    public static final String algorithmName = Sha256Hash.ALGORITHM_NAME;

    public static final int hashIterations = 3;

    public static HashedCredentialsMatcher getHashMatcher() {
        HashedCredentialsMatcher hashMatcher = new HashedCredentialsMatcher();
        hashMatcher.setHashAlgorithmName(algorithmName);
        hashMatcher.setStoredCredentialsHexEncoded(true);
        hashMatcher.setHashIterations(hashIterations);
        return hashMatcher;
    }

    public static CrowUser encrypt(CrowUser user) {
        user.setSalt(generateSalt());
        if(Strings.isNullOrEmpty(user.getPassword())) {
            user.setPassword(user.getMobile());
        }
        String newPassword = encrypt(user.getPassword(), user.getSalt());
        user.setPassword(newPassword);

        return user;
    }

    public static String encrypt(String rawPassword, String salt) {
        return new SimpleHash(
                algorithmName,
                rawPassword,
                salt,
                hashIterations).toString();
    }

    public static String generateSalt() {
        return randomNumberGenerator.nextBytes().toHex();
    }

}
